<template>
  <div>
    <div class="gl_ml_15 gl_mb_20">
      <span class="gl_mr_20 gl_ft_weight gl_fs_16">来源分组</span>
      <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="newGroup">新增分组</el-button>
    </div>
    <div class="gl_ml_15 outer">
      <!-- 默认分组 -->
      <div>
        <div v-for="(item, index) in defaultGroup" :key="index" class="default">
          <div class="inner_one">
            <span class="icons" />
            <span class="title">{{ item.name }}</span>
          </div>
          <div class="inner_two">系统默认，无法修改</div>
        </div>
      </div>
      <!-- 已添加分组 -->
      <div>
        <div v-for="(item, index) in groupList" :key="index" class="group">
          <div class="inner">
            <span class="icons gl_mr_10" />
            <span class="content">{{ item.name }}</span>
            <span class="iconfont icon_shanchu gl_mx_5" style="color:#0076CB" @click="deleteIcon(item.id)" />
            <span class="iconfont icon_xiugai" style="color:#0076CB" @click="editIcon(item)" />
          </div>
        </div>
      </div>
    </div>
    <div class="gl_ml_15 gl_mt_30">
      <span class="gl_mr_20 gl_ft_weight gl_fs_16">来源类型</span>
      <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="newSource">新增类型</el-button>
    </div>
    <div class="gl_mt_15">
      <el-table v-loading="tableLoading" :data="tableData" class="gl_table_noBorder gl_mt_15" size="mini" style="width: 100%;">
        <el-table-column label="来源类型名称" prop="name" min-width="120" />
        <el-table-column label="分组名称" prop="sourceGroup.name" min-width="120" />
        <el-table-column label="创建时间" :min-width="135">
          <template slot-scope="{row}">
            <span v-if="row.creationTime">
              {{ row.creationTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}
            </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" width="120">
          <template slot-scope="{ row }">
            <el-button size="mini" type="text" @click="clickEdit(row)">编辑</el-button>
            <el-button size="mini" type="text" style="color:#FF3434" @click="clickDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row class="gl_pt_15" style="text-align: right;">
        <el-pagination
          :current-page="sourceQO.Page"
          :page-size="sourceQO.MaxResultCount"
          :total="total"
          layout="total,sizes,prev,pager,next,jumper"
          :page-sizes="[10, 20, 30, 40]"
          @size-change="sizeChange"
          @current-change="pageIndexChange"
        />
      </el-row>

      <!-- 新增组别 -->
      <el-dialog
        :title="groupTitle"
        class="gl_dialog_TitleLine gl_dl_footer"
        :visible.sync="groupDialogVisible"
        :close-on-click-modal="false"
        :before-close="groupCancelDialog"
        width="550px"
      >
        <el-form ref="group" :model="groupDTO" label-width="100px" size="mini" style="padding: 30px 30px 40px 30px" :rules="group_Rules">
          <el-form-item label="分组名称" prop="name">
            <el-input v-model.trim="groupDTO.name" placeholder="请输入分组名称" maxlength="10" size="mini" type="text" oninput="if(value.length > 10) value.substring(0, 10)" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="groupCancelDialog()">{{ $t('button.cancel') }}</el-button>
          <el-button size="mini" type="primary" :loading="groupbtnLoading" @click="groupConfirm()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 新增来源 -->
      <el-dialog
        :title="sourceTitle"
        class="gl_dialog_TitleLine gl_dl_footer"
        :visible.sync="sourceDialogVisible"
        :close-on-click-modal="false"
        :before-close="sourceCancelDialog"
        width="550px"
      >
        <el-form ref="source" :model="sourceDTO" label-width="100px" size="mini" style="padding: 30px 30px 40px 30px" :rules="source_Rules">
          <el-form-item label="来源渠道" prop="sourceGroupId">
            <el-select v-model="sourceDTO.sourceGroupId" size="mini" style="width: 100%">
              <el-option v-for="item in totalGroupList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="来源名称" prop="name">
            <el-input v-model.trim="sourceDTO.name" placeholder="请输入来源名称" maxlength="10" size="mini" type="text" oninput="if(value.length > 10) value.substring(0, 10)" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="sourceCancelDialog()">{{ $t('button.cancel') }}</el-button>
          <el-button size="mini" type="primary" :loading="sourcebtnLoading" @click="sourceConfirm()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import validator from '@/lib/validate/index.js';
import {
  Api_GET_ClubCustomerSourceGroupQO, // 分页获取分组信息
  Api_GET_ClubCustomerSourceQO, // 分页获取来源信息
  SourceGroupInput // 创建分组
} from '@/lib/form/hall/swaggerForm';
import {
  api_GET_ClubCustomerSourceGroup, // 分页获取分组信息
  api_POST_ClubCustomerSourceGroup, // 创建分组
  api_PUT_ClubCustomerSourceGroup, // 修改分组
  api_DELETE_ClubCustomerSourceGroup, // 删除分组
  api_GET_ClubCustomerSource, // 分页获取来源信息
  api_POST_ClubCustomerSource, // 创建来源
  api_PUT_ClubCustomerSource, // 修改来源
  api_DELETE_ClubCustomerSource // 删除来源
} from '@/extend/api/hallswaggerApi/app';
export default {
  data() {
    return {
      defaultGroup: [],
      groupList: [],
      totalGroupList: [],
      groupQO: new Api_GET_ClubCustomerSourceGroupQO(),
      sourceQO: new Api_GET_ClubCustomerSourceQO(),
      tableData: [],
      total: 0,
      tableLoading: false,
      groupId: '',
      groupTitle: '添加来源分组',
      groupDialogVisible: false,
      groupDTO: new SourceGroupInput(),
      groupbtnLoading: false,
      group_Rules: {
        name: [validator.required('分组名称不能为空', 'blur')]
      },
      sourceId: '',
      sourceTitle: '添加来源',
      sourceDialogVisible: false,
      sourceDTO: {
        name: '',
        sourceGroupId: ''
      },
      sourcebtnLoading: false,
      source_Rules: {
        sourceGroupId: [validator.required('所属分组不能为空', 'blur')],
        name: [validator.required('来源名称不能为空', 'blur')]
      }
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  created() {
    this.getSourceList();
    this.getGroupList();
  },
  methods: {
    // 若没有字典信息，外部可直接调用方法获取字典数据
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    // 获取来源列表
    getSourceList(page) {
      this.sourceQO.Page = page || 1;
      this.sourceQO.SkipCount = (this.sourceQO.Page - 1) * this.sourceQO.MaxResultCount;
      this.sourceQO.IncludeSourceGroup = true;
      this.tableLoading = true;
      api_GET_ClubCustomerSource(this.sourceQO).then(res => {
        this.tableLoading = false;
        this.tableData = res.items;
        this.total = res.totalCount;
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 获取分组列表
    getGroupList() {
      const that = this;
      this.groupQO.Page = 1;
      this.groupQO.SkipCount = 0;
      this.groupQO.MaxResultCount = 999;
      api_GET_ClubCustomerSourceGroup(this.groupQO).then(res => {
        this.totalGroupList = res.items;
        this.defaultGroup = [];
        this.groupList = [];
        this.totalGroupList.map(item => {
          item.isSystemDefault === 'True' ? that.defaultGroup.push(item) : that.groupList.push(item);
        });
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    newGroup() {
      this.groupTitle = '新增来源分组';
      this.groupDialogVisible = true;
    },
    editIcon(item) {
      this.groupTitle = '编辑来源分组';
      this.groupDialogVisible = true;
      this.groupId = item.id;
      this.groupDTO.name = item.name;
    },
    // 新增编辑分组
    groupConfirm() {
      const that = this;
      that.$refs.group.validate(valid => {
        if (valid) {
          that.groupId ? that.editGroup() : that.addGroup();
        } else {
          return false;
        }
      });
    },
    addGroup() {
      this.groupbtnLoading = true;
      api_POST_ClubCustomerSourceGroup(this.groupDTO).then(res => {
        this.groupDialogVisible = false;
        this.groupbtnLoading = false;
        this.$message({ type: 'success', message: '添加成功' });
        this.groupDTO = new SourceGroupInput();
        this.getGroupList();
      }, error => {
        this.groupbtnLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    editGroup() {
      this.groupbtnLoading = true;
      api_PUT_ClubCustomerSourceGroup({ 'sourceGroupId': this.groupId }, this.groupDTO).then(res => {
        this.groupDialogVisible = false;
        this.groupbtnLoading = false;
        this.$message({ type: 'success', message: '修改成功' });
        this.groupDTO = new SourceGroupInput();
        this.getGroupList();
        this.groupId = '';
      }, error => {
        this.groupbtnLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    groupCancelDialog() {
      this.groupId = '';
      this.groupDTO = new SourceGroupInput();
      this.groupDialogVisible = false;
    },
    // 删除分组
    deleteIcon(id) {
      const that = this;
      that.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_ClubCustomerSourceGroup({ 'sourceGroupId': id }).then(res => {
            that.$message({ type: 'success', message: '删除成功' });
            that.getGroupList();
            that.getSourceList();
          }, error => {
            const _msg = error.error.message || error.message;
            that.$message({ type: 'error', message: _msg });
          });
        })
        .catch(() => {
        });
    },
    newSource() {
      this.sourceTitle = '添加来源';
      this.sourceDialogVisible = true;
      this.getGroupList();
    },
    // 编辑来源
    clickEdit(item) {
      this.sourceTitle = '编辑来源';
      this.sourceId = item.id;
      this.sourceDialogVisible = true;
      this.sourceDTO.name = item.name;
      this.sourceDTO.sourceGroupId = item.sourceGroup.id;
    },
    sourceConfirm() {
      const that = this;
      that.$refs.source.validate(valid => {
        if (valid) {
          that.sourceId ? that.editSource() : that.addSource();
        } else {
          return false;
        }
      });
    },
    editSource() {
      this.sourcebtnLoading = true;
      api_PUT_ClubCustomerSource({ 'sourceId': this.sourceId }, this.sourceDTO).then(res => {
        this.sourceDialogVisible = false;
        this.sourcebtnLoading = false;
        this.$message({ type: 'success', message: '修改成功' });
        this.sourceDTO = { name: '', sourceGroupId: '' };
        this.getSourceList();
        this.sourceId = '';
      }, error => {
        this.sourcebtnLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    addSource() {
      this.sourcebtnLoading = true;
      api_POST_ClubCustomerSource({ 'sourceGroupId': this.sourceDTO.sourceGroupId }, { 'name': this.sourceDTO.name }).then(res => {
        this.sourceDialogVisible = false;
        this.sourcebtnLoading = false;
        this.$message({ type: 'success', message: '添加成功' });
        this.sourceDTO = { sourceGroupId: '', name: '' };
        this.getSourceList();
      }, error => {
        this.sourcebtnLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 删除来源
    clickDelete(id) {
      const that = this;
      that.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.tableLoading = true;
          api_DELETE_ClubCustomerSource({ 'sourceId': id }).then(res => {
            that.tableLoading = false;
            that.$message({ type: 'success', message: '删除成功' });
            that.getSourceList();
          }, error => {
            that.tableLoading = false;
            const _msg = error.error.message || error.message;
            that.$message({ type: 'error', message: _msg });
          });
        })
        .catch(() => {
        });
    },
    sourceCancelDialog() {
      this.sourceId = '';
      this.sourceDTO = { name: '', sourceGroupId: '' };
      this.sourceDialogVisible = false;
    },
    // 分页
    sizeChange(MaxResultCount) {
      this.sourceQO.MaxResultCount = MaxResultCount;
      this.getSourceList();
    },
    pageIndexChange(currentPage) {
      this.getSourceList(currentPage);
    }
  }
};
</script>

<style lang="scss" scoped>
.icons {
  display: inline-block;
  width: 16px;
  height: 16px;
  vertical-align: middle;
  background-image: url('../../../assets/images/hall/fenzuicon.png');
  background-size: 16px 16px;
  background-repeat: no-repeat;
}
.outer {
  min-height: 104px;
}
.default{
  display: inline-block;
  width: 294px;
  height: 96px;
  background: #F5F8FF;
  border-radius: 6px;
  margin: 0px 16px 8px 0px;
  box-sizing: border-box;
  padding: 10px 0px 0px 10px;
  .inner_one {
    display: flex;
    align-items: center;
    height: 20px;
    line-height: 20px;
    margin-bottom: 20px;
  }
  .title {
    margin-left: 10px;
    font-family: 'PingFang SC';
    font-size: 16px;
    line-height: 18px;
    color: #0076CB;
  }
  .inner_two {
    font-family: 'PingFang SC';
    margin-left: 26px;
    font-size: 14px;
    color: #616161;
  }
}
.group {
  display: inline-block;
  width: 294px;
  height: 80px;
  background: #F5F8FF;
  border-radius: 6px;
  line-height: 80px;
  box-sizing: border-box;
  padding: 0px 15px 0px 10px;
  margin: 0px 16px 8px 0px;
  .inner {
    width: 100%;
    display: flex;
    align-items: center;
    .content {
      display: inline-block;
      flex: 1;
      font-family: 'PingFang SC';
      font-size: 16px;
      color: #0076CB;
    }
  }
}
</style>
